package com.blog.back.service.impl;

import com.blog.back.config.CacheArticleLinkedList;
import com.blog.back.dao.ArticleInfoDao;
import com.blog.back.dao.ext.ArticleExtMapper;
import com.blog.back.dao.ext.ArticleDTOMapper;
import com.blog.back.redis.RedisUtils;
import com.blog.back.service.ArticleInfoService;
import com.blog.dto.ArticleDTO;
import com.blog.dto.PageDTO;
import com.blog.exception.RRException;
import com.blog.utils.CopyUtil;
import com.blog.utils.PageUtils;
import com.blog.utils.Query;
import com.blog.utils.RedisKeys;
import com.blog.vo.ArticleDetailVO;
import com.blog.vo.ArticleHelperVO;
import com.blog.vo.ArticleListVO;
import com.blog.vo.ArticleVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jdk.nashorn.internal.runtime.logging.Logger;
import lombok.extern.java.Log;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.blog.back.dao.ArticleDao;
import com.blog.entity.ArticleEntity;
import com.blog.back.service.ArticleService;
import org.springframework.util.StringUtils;


// @Service("articleService")
// @Log4j2
@Service
@Slf4j
public class ArticleServiceImpl extends ServiceImpl<ArticleDao, ArticleEntity> implements ArticleService {

    @Autowired
    ArticleDao articleDao;

    @Autowired
    ArticleExtMapper articleExtMapper;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    PageHelper pageHelper;

    @Autowired
    ArticleDTOMapper articleDTOMapper;

    @Autowired
    ArticleInfoService articleInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ArticleEntity> page = this.page(
                new Query<ArticleEntity>().getPage(params),
                new QueryWrapper<ArticleEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询单个文章
     *
     * @param id 主键ID
     * @return
     */
    @Override
    public ArticleEntity getById(Long id) {
        Object obj = redisUtils.get(RedisKeys.getArticleKey(id));
        if (!StringUtils.isEmpty(obj)) {
            articleInfoService.mergeInfoHit(id);
            return (ArticleEntity) obj;
        }
        ArticleEntity articleEntity = articleDao.selectById(id);
        if (!StringUtils.isEmpty(articleEntity)) {
            // log.info("{} ", id);
            articleInfoService.mergeInfoHit(id);
            redisUtils.set(RedisKeys.getArticleKey(id), articleEntity, 60 * 60 * 24);
        }
        return articleEntity;
    }

    @Override
    public ArticleListVO listByUserPage(PageDTO pageDTO) {
        if (!check(pageDTO)) throw new RRException("参数非法");
        System.out.println(pageDTO);
        PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
        List<ArticleDTO> list = articleDTOMapper.selectByUser(pageDTO.getUserId());
        PageInfo<ArticleDTO> pageInfo = new PageInfo<>(list);
        ArticleListVO listVO = new ArticleListVO(pageInfo);
        return listVO;
    }


    /**
     * 根据用户id 与关键字查询文章
     *
     * @param pageDTO
     * @return
     */
    @Override
    public ArticleListVO listByUserWithKeywordsPage(PageDTO pageDTO) {
        if (!check(pageDTO)) throw new RRException("参数非法");
        PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
        List<ArticleDTO> articleDTOS = articleDTOMapper.selectByUserLikeOther(pageDTO.getUserId(), pageDTO.getKeywords());
        PageInfo<ArticleDTO> pageInfo = new PageInfo<>(articleDTOS);
        ArticleListVO listVO = new ArticleListVO(pageInfo);
        return listVO;
    }

    @Override
    public ArticleDetailVO getArticleDetailById(Long articleId, Long usersId) {
        ArticleEntity target = getById(articleId);

        List<ArticleHelperVO> list = CacheArticleLinkedList.getPreAndNext(articleId);
        // ArticleEntity next = articleExtMapper.selectNextArticleByArticleIdAndUserId(articleId, usersId);
        // ArticleEntity prev = articleExtMapper.selectPrevArticleByArticleIdAndUserId(articleId, usersId);
        return new ArticleDetailVO(target, list.get(0), list.get(1));
    }


    /**
     * 显示点击量前三的文章
     *
     * @param userId
     */
    @Override
    public List<ArticleVO> litsMostArticles(Long userId) {
        if (userId == null) throw new RRException("非法参数");

        Object obj = redisUtils.get(RedisKeys.getMosthitkey(userId));
        if (!StringUtils.isEmpty(obj)) {
            return (List<ArticleVO>) obj;
        }
        return selectScheduled(userId);
    }

    /**
     * 定时任务，每天都刷新到redis缓存中一次
     *
     * @param userId
     */
    @Override
    public List<ArticleVO> selectScheduled(Long userId) {
        List<ArticleDTO> list = articleDTOMapper.selectMostArticles(userId);
        if (list == null || list.size() == 0) return null;
        List<ArticleVO> articleVOS = CopyUtil.copyList(list, ArticleVO.class);
        redisUtils.set(RedisKeys.getMosthitkey(userId), articleVOS, 60 * 60 * 24);
        log.info("进入缓存了 {}", RedisKeys.getMosthitkey(userId));
        return articleVOS;
    }

    @Override
    public ArticleDetailVO getIntroduceByUserId(Long usersId) {
        ArticleEntity entity = articleExtMapper.selectIntroduceByUserId(usersId);
        return new ArticleDetailVO(entity, null, null);
    }

    @Override
    public List<ArticleEntity> listDesc() {
        QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("is_introduce", 1)
                .ne("is_deleted", 1)
                .orderByDesc("article_id");
        return articleDao.selectList(queryWrapper);
    }
}